package ro.cityprojects.adminloc.dao;

import org.springframework.util.CollectionUtils;
import ro.cityprojects.adminloc.entities.Person;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Set;

@Repository
@SuppressWarnings("unchecked")
public class PersonDAOImpl extends BaseDAO<Integer, Person> implements PersonDAO {

    private static final Logger log = LoggerFactory.getLogger(PersonDAOImpl.class);

    @Override
    public void save(Person user) {
        saveEntity(user);
    }

    @Override
    public Person get(Integer id) {
        return get(Person.class, id);
    }

    @Override
    public Set<Person> getAll(String filterName, String filterValue) {
        return getAll(filterName, filterValue, Person.class);
    }

    @Override
    public void update(Person entity) {
        updateEntity(entity);
    }

    @Override
    public void delete(Integer primaryKey) {
        deleteEntity(Person.class, primaryKey);
    }

    @Override
    public Person getByUserName(String userName) {
        List<Person> users = hibernateTemplate.findByNamedQueryAndNamedParam("Person.byUserName", "userName", userName);
        if (CollectionUtils.isEmpty(users)) {
            log.warn("There is no person named '{}'", userName);
            return null;
        }

        return users.get(0);
    }

    @Override
    public List<Person> getByName(String name) {
        if (name == null) {
            return hibernateTemplate.find("FROM Person");
        } else {
            return hibernateTemplate.findByNamedQueryAndNamedParam("Person.byName", "name", '%' + name.toLowerCase() + '%');
        }
    }
}
